<script setup>
/**
 * @name: 新版模板广场
 * @description：FormworkSquareContent
 */

// vue相关
import {
  computed,
  nextTick,
  onMounted,
  onUnmounted,
  reactive,
  ref,
  watch,
} from "vue";
import request from "@/common/utils/request";
import { nanoid } from "nanoid";

// 路由
import { useRouter, useRoute } from "vue-router";
import { useStore } from "vuex";
const route = useRoute();
const router = useRouter();
import { message, Modal, Empty, notification } from "ant-design-vue";
// 获取当前日期, 前三天 和前七天日期的方法
import { getPreviousDates } from "@/views/shotstack/utils/index.js";
import { onBeforeRouteLeave } from "vue-router";

// 组件
import { PlusOutlined } from "@ant-design/icons-vue";
// 提取文案提示框
import Extractcopy from "./modules/Dialogs/Extractcopy.vue";
// 提取文字弹窗
import ExtractText from "./modules/Dialogs/Extracttext.vue";

// icon
import { SearchOutlined } from "@ant-design/icons-vue";

// 头部删选标签
import filtersComponent from "./components/filtersComponent.vue";
// 我的灵感库
import afflatus from "./modules/afflatus/afflatus.vue";
// 爆款文案库
import ExplosiveText from "./modules/ExplosiveText/ExplosiveText.vue";
// 黄金前三秒
import Goldenopening from "./modules/Goldenopening/Goldenopening.vue";
import store from "@/store/index.js";
// 充值弹窗
import vipModal from '@/socialMedia/Vip/vipModal.vue'
const vipVisible = ref(false)

// 获得列表选择的数据
const emit = defineEmits("getText:text", "importUse:item");

const props = defineProps({
  // 是否展示头部蓝色标题卡片
  showTitleCart: {
    type: Boolean,
    default: true,
  },
  // 是否开启勾选模式(相当于开启组件模式)
  isSelect: {
    type: Boolean,
    default: false,
  },
  // 设置单选或是多选
  selectType: {
    type: String,
    default: "checkbox",
  },
});

// 数据合集
const state = reactive({
  // 当前tab栏所在的选项 1 - 爆款 2 - 黄金 3 - 我的
  activeKey: "1",
  // 筛选时间 0 - 全部 1 - 近一日; 2 - 近三日; 3 - 周榜
  activeTime: "0",
  time: ["", ""],
  // 筛选条件的 开始和结束时间
  startTime: "",
  endTime: "",
  // 关键词搜索
  text: "",
  // 搜索按钮加载状态
  serchLoding: false,
  // 是否禁用日期
  pickerDisable: false,
  // 是否筛选收藏 0 默认 1 收藏
  filter_collect: 0,
  // 标签列表
  filterArr: [],
  hotFilterList: [
    {
      name: "视频总榜",
      id: 1,
      key: 101,
    },
    {
      name: "低粉爆款",
      id: 2,
      key: 102,
    },
    {
      name: "高涨粉率",
      id: 3,
      key: 104,
    },
    {
      name: "高点赞率",
      id: 4,
      key: 105,
    },
  ],
  ranking_type: 101, //默认视频总榜
});

// 标签组件
const filtersComponentRef = ref(null);
// 爆款文案库组件
const explosiveTextRef = ref(null);
// 我的灵感库组件
const afflatusRef = ref(null);

// 选择筛选的时间
const selectTime = (val) => {
  // debugger
  state.activeTime = state.activeTime == val ? "" : val;

  if (state.activeTime == "" || state.activeTime == "0") {
    state.time = ["", ""];
    state.startTime = "";
    state.endTime = "";
  }
  // 改变后 重新获取数据
  nextTick(() => {
    resetPage();
    getItemList();
  });
};

// 根据
watch(
  () => state.activeTime,
  (nv, ov) => {
    // 有值的时候, 手动调用修改 startTime 和 endTime, 置空筛选日期的时间, 禁用掉日期
    if (nv) {
      switch (nv) {
        case "1":
          state.startTime = getPreviousDates(new Date(), 1);
          state.endTime = getPreviousDates(new Date(), 1);
          state.time = [state.startTime, state.endTime];
          break;
        case "2":
          state.startTime = getPreviousDates(new Date(), 3);
          state.endTime = getPreviousDates(new Date(), 1);
          state.time = [state.startTime, state.endTime];
          break;
        case "3":
          state.startTime = getPreviousDates(new Date(), 7);
          state.endTime = getPreviousDates(new Date(), 1);
          state.time = [state.startTime, state.endTime];
          break;
      }
    }
  },
  {
    immediate: true,
  }
);

// 选择的标签列表
const tag_ids = computed(() => {
  return filtersComponentRef.value?.getSelectTages;
});

onMounted(() => {
  getTags();
});

// 获取筛选标签
const getTags = async () => {
  const res = await request.get(
    "work_ai",
    "/user/shotstack/inspirationText/groupTags"
  );
  console.log(res, "标签列表");
  state.filterArr = res.result;
  nextTick(() => {
    filtersComponentRef.value && filtersComponentRef.value.initTag();
  });
};

// 日期选择
const timeChange = (data, dataString) => {
  state.activeTime = "";
  state.startTime = dataString[0];
  state.endTime = dataString[1];
};

// 提取视频文案弹窗
const ExtractcopyRef = ref(null);
// 提取视频文字弹窗
const ExtractTextRef = ref(null);

// 打开文案提取
const openExtractcopyRef = () => {
  if (store.getters.isVersionExpired) {
    notification.warn({ message: "您的套餐已到期", duration: 2 });
   vipVisible.value = true
  } else {
    ExtractcopyRef.value.openDialog();
  }
};

// 手动添加文案
const addCopyManually = () => {
  if (store.getters.isVersionExpired) {
    notification.warn({ message: "您的套餐已到期", duration: 2 });
      vipVisible.value = true

  } else {
    const unique_id = nanoid();
    router.push(
      `/mixedCutCreat?id=${-1}&key=id&viewType=2&openType=creat&isAi=true&unique_id=${unique_id}`
    );
  }
};

const desc = computed(() => {
  if (state.activeKey == "1") {
    return {
      title: "图生视频",
      desc: "搜罗全网爆款文案库,寻找符合自己行业的灵感资源，使用AI 快速打造原创爆款视频",
    };
  } else if (state.activeKey == "2") {
    return {
      title: "视频黄金前三秒",
      desc: "搜罗全网爆款文案库,寻找符合自己行业的灵感资源，使用AI 快速打造原创爆款视频",
    };
  } else {
    return {
      title: "我的灵感库",
      desc: "提取全网创作和优秀案例，让灵感到创作更简单，极大提升创作效率。",
    };
  }
});

// 点击搜索
const getItemList = () => {
  if (state.activeKey == 1) {
    // 爆款文案库
    explosiveTextRef.value && explosiveTextRef.value.getExplosiveTextList();
  } else if (state.activeKey == 3) {
    // 我的灵感库
    afflatusRef.value && afflatusRef.value.getAfflatusList();
  }
};

// 重置当前页码
const resetPage = () => {
  if (state.activeKey == 1) {
    explosiveTextRef.value && explosiveTextRef.value.resetPage();
  } else if (state.activeKey == 3) {
    afflatusRef.value && afflatusRef.value.resetPage();
  } else {
  }
};

// 清空搜索条件
const resetfilterData = () => {
  state.time = ["", ""];
  state.startTime = "";
  state.endTime = "";
  state.text = "";
  state.activeTime = "0";
  state.filter_collect = 0;
  resetPage();
};

// 点击清空
const resetSerchData = () => {
  // 重置搜索的条件
  resetfilterData();
  nextTick(() => {
    getItemList();
  });
};

// 切换到 我的灵感库, 清空这些筛选数据
const activeKeyChange = (key) => {
  resetfilterData();
  state.ranking_type = 101;
};

// 筛选标签改变, 发送请求
const tagsChange = () => {
  resetPage();
  state.activeKey != 3 && getItemList();
};

// 提取视频文案提交成功事件
const submitFn = (id) => {
  console.log("提交成功");
  ExtractTextRef.value && ExtractTextRef.value.openDialog(id);
};

// 我的灵感库 查看详情
const isEditMyAfflatus = (id) => {
  ExtractTextRef.value && ExtractTextRef.value.openDialog(id);
};

// 编辑弹窗点击确定
const dialogSubmit = () => {
  // 重新获取列表数据
  nextTick(() => {
    getItemList();
  });
};

const bye = ref(true);
// 抖音热点榜筛选
const selectHotKey = (info) => {
  state.ranking_type = info.key;
  explosiveTextRef.value &&
    explosiveTextRef.value.getExplosiveTextList(info.key);
};

// 勾选导入的文案
const importSelectItem = () => {
  let list;
  // 爆款文案库
  if (state.activeKey != 3) {
    list = explosiveTextRef.value.getSelects();
  } else {
    // 我的灵感库
    list = afflatusRef.value.getSelects();
  }
  if (!list.length) return message.error("请勾选想要导入的文案");
  console.log(list, "勾选的文案");
  let text;
  if (props.selectType == "checkbox") {
    text = list.map((ele) => ele.text);
    emit("getText", text);
  } else {
    text = list.map((ele) => ele.text).join(",");
    emit("getText", text);
  }
};

// 导出单项
const importUse = (item) => {
  emit("importUse", item);
};

onBeforeRouteLeave((to, from, next) => {
  bye.value = false;
  next(true);
});
</script>

<template v-if="bye">
  <div class="FormworkSquareContent" ref="FormworkSquareContent">
    <!-- 模板广场头部 start -->
    <div class="smart-clip-header" v-if="props.showTitleCart">
      <div class="smart-clip-header-title_top">{{ desc.title }}</div>
      <div class="smart-clip-header-desc">
        {{ desc.desc }}
      </div>
    </div>

    <a-tabs v-model:activeKey="state.activeKey" @change="activeKeyChange">
      <a-tab-pane key="1" tab="爆款文案库"></a-tab-pane>
      <!-- <a-tab-pane key="2" tab="黄金前三秒" disabled></a-tab-pane> -->
      <a-tab-pane key="3" tab="我的灵感库"></a-tab-pane>
    </a-tabs>
    <div class="content_box">
      <!-- 头部筛选条件 -->
      <div class="tags_box">
        <!-- 行业类型等标签筛选 -->
        <filtersComponent ref="filtersComponentRef" v-show="state.activeKey != 3" :tags="state.filterArr"
          @tagsChange="tagsChange"></filtersComponent>
        <!-- 抖音热点榜筛选 -->
        <div class="douyin_hot" v-if="state.activeKey != 3">
          <span class="filter_item_title">抖音热点榜：</span>
          <div class="filter_item_list">
            <div class="filter_item_list_item" v-for="(hot, index) in state.hotFilterList" @click="selectHotKey(hot)"
              :key="hot.id" :class="{
                active_select_hotkey: state.ranking_type == hot.key,
              }">
              {{ hot.name }}
            </div>
          </div>
        </div>
        <!-- 日期筛选 -->
        <div class="filter_box">
          <!-- 导入所选文案, 只有当作为弹窗的时候才会展示 -->
          <a-button v-if="!props.showTitleCart" @click="importSelectItem" type="primary" ghost :size="size">
            <template #icon>
              <PlusOutlined />
            </template>
            导入所选文案
          </a-button>
          <div class="date_box" v-if="state.activeKey != 3">
            <div class="date_item date_left" @click="selectTime('0')" :class="{
                active_select_time: state.activeTime == '0',
              }" :style="{
                'border-right-color':
                  state.activeTime == 1 ? 'var(--ss-primary-6)' : '#dddddd',
              }">
              全部
            </div>
            <div class="date_item" @click="selectTime('1')" :class="{
                active_select_time: state.activeTime == '1',
              }">
              近1日
            </div>
            <div class="date_item" :class="{
                active_select_time: state.activeTime == '2',
              }" :style="{
                'border-left-color':
                  state.activeTime == 1 ? 'var(--ss-primary-6)' : '#dddddd',
                'border-right': 'none',
              }" @click="selectTime('2')">
              近3日
            </div>
            <div class="date_item date_right" :class="{
                active_select_time: state.activeTime == '3',
              }" :style="{
                'border-left-color':
                  state.activeTime == 2 ? 'var(--ss-primary-6)' : '#dddddd',
              }" @click="selectTime('3')">
              周榜
            </div>
          </div>
          <!-- 只有我的灵感才有的提取文案按钮 -->
          <!-- v-if="state.activeKey == 3" -->

          <div class="btns_box">
            <template v-if="props.showTitleCart">
              <a-button @click="openExtractcopyRef" v-if="state.activeKey == 3" type="primary" ghost :size="size">
                <template #icon>
                  <PlusOutlined />
                </template>
                提取文案
              </a-button>

              <!-- v-if="false" -->
              <a-button @click="addCopyManually" type="primary" ghost :size="size" style="margin-bottom: 14px"
                v-if="state.activeKey == 3">
                <template #icon>
                  <PlusOutlined />
                </template>
                手动添加文案
              </a-button>
            </template>
          </div>
          <!-- 所有tab 都有的名称日期搜索 -->
          <div class="right_serch_box">
            <a-input allow-clear @change="(e) => e.type == 'click' && getMediaList()" style="width: 247px"
              v-model:value="state.text" placeholder="请输入关键字搜索">
              <template #prefix>
                <SearchOutlined />
              </template>
            </a-input>

            <!-- 日期  -->
            <a-range-picker @change="timeChange" :disable="state.pickerDisable" format="YYYY-MM-DD"
              valueFormat="YYYY-MM-DD" style="width: 247px; margin: 0 10px" v-model:value="state.time" show-time />
            <a-button @click="resetSerchData" style="margin-right: 10px">清空</a-button>
            <a-button type="primary" :loading="state.serchLoding" @click="
                () => {
                  resetPage();
                  getItemList();
                }
              ">查询</a-button>
          </div>
        </div>
      </div>

      <!-- 爆款文案库 -->
      <template v-if="state.activeKey == 1">
        <ExplosiveText ref="explosiveTextRef" @importUse="importUse" :startTime="state.startTime"
          :endTime="state.endTime" :tag_ids="tag_ids" :text="state.text" :filter_collect="state.filter_collect"
          :isSelect="props.isSelect" :selectType="props.selectType"></ExplosiveText>
      </template>

      <!-- 黄金前三秒 -->
      <template v-if="state.activeKey == 2">
        <Goldenopening></Goldenopening>
      </template>

      <!-- 我的灵感库 -->
      <template v-if="state.activeKey == 3">
        <afflatus ref="afflatusRef" :startTime="state.startTime" :endTime="state.endTime" :text="state.text"
          @isEditMyAfflatus="isEditMyAfflatus" @importUse="importUse" :isSelect="props.isSelect"
          :selectType="props.selectType"></afflatus>
      </template>
    </div>
  </div>
  <!-- 提取视频文案弹窗 -->
  <Extractcopy ref="ExtractcopyRef" key="ExtractcopyRef" @submitFn="submitFn" :startTime="state.startTime"
    :endTime="state.endTime"></Extractcopy>

  <!-- 提取视频文字弹窗 -->
  <ExtractText ref="ExtractTextRef" key="ExtractTextRef" @dialogSubmit="dialogSubmit"></ExtractText>
  <!-- 充值弹窗 -->
  <vipModal :visible="vipVisible" @close="vipVisible = false"></vipModal>

</template>

<style lang="less" scoped>
.FormworkSquareContent {
  padding: 14px;

  // 主要内容区域
  .content_box {
    background-color: #fff;
    padding: 14px;
    min-width: 1300px;

    .tags_box {
      // 日期筛选
      .filter_box {
        margin: 0 0 25px 0;
        display: flex;
        justify-content: space-between;

        .date_box {
          .date_item {
            width: 88px;
            height: 30px;
            // background: pink;
            display: inline-block;
            text-align: center;
            line-height: 30px;
            border: 1px solid #dfdede;
            cursor: pointer;

            &:nth-child(2) {
              border-left: none;
              border-right: none;
            }

            &.active_select_time {
              // border-color:red ;
              border-color: var(--ss-primary-6) !important;
            }
          }

          .date_left {
            border-radius: 8px 0 0 8px;
          }

          .date_right {
            border-radius: 0 8px 8px 0;
          }
        }

        .btns_box {
          display: flex;
          gap: 15px;
        }

        .right_serch_box {
        }
      }

      .douyin_hot {
        display: flex;
        margin-bottom: 10px;

        .filter_item_title {
          color: rgba(28, 31, 35, 0.6);
          padding: 4px 10px;
          margin-right: 16px;
          margin-bottom: 8px;
        }

        .filter_item_list {
          display: flex;
          align-items: center;
          margin-bottom: 8px;

          .filter_item_list_item {
            padding: 4px 10px;
            margin-right: 16px;
            margin-bottom: 8px;
            cursor: pointer;
            color: rgba(28, 31, 35, 0.8);

            &:hover {
              background-color: var(--ss-tag-bgc-color);
              color: var(--ss-primary-color);
              border-radius: 20px;
            }

            &.active_select_hotkey {
              background-color: var(--ss-tag-bgc-color);
              color: var(--ss-primary-color);
              border-radius: 20px;
            }
          }
        }
      }
    }
  }

  // 头部
  .smart-clip-header {
    padding: 30px;
    border-radius: 12px;
    // height: 180px;
    min-width: 1140px;
    // margin-top: 20px;
    background: linear-gradient(220deg, #f3f7ff, rgba(159, 191, 255, 0.4));
    display: flex;
    flex-direction: column;

    .smart-clip-header-title_top {
      font-size: 24px;
      color: #0c0d0e;
      line-height: 1.5;
    }

    .smart-clip-header-desc {
      font-size: 14px;
      color: #737a87;
      margin-top: 5px;
      line-height: 1.5;
    }

    .smart-clip-header-btngroup {
      margin-top: 15px;
    }
  }
}
</style>
